package IOStream_etc.BufferStream_etc;

import org.junit.Test;

import java.io.*;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/29 12:05
 * 说明：使用节点流和使用缓冲流复制视频的效率差异
 */

public class CopyFileTest {

    @Test
    public void testSpendTime(){
        long start = System.currentTimeMillis();
        String src = "";
        String des = "";
        long end = System.currentTimeMillis();
        copyFileWithFileStream(src, des);
        System.out.println(end - start);
    }


    /**
     * 使用缓冲流复制文件
     */
    public void copyFileWithBufferedStream(String src, String des){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 1. 创建相关File类的对象
            File srcFile = new File(src);
            File desFile = new File(des);
            // 2. 创建相关字节流、缓冲流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(desFile, true);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            // 3. 数据的读入和写出
            byte[] buffer = new byte[50];
            int len; // 记录每次读入到buffer中字节的个数
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 4. 关闭资源
            // 先关外层流
            try {
                if (bos != null) bos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if (bis != null) bis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 再关内层流。由于外层流的关闭也会关闭内层流，因此内层流的关闭操作可以省去
//        fos.close();
//        fis.close();
        }
    }
    /**
     * 使用节点流（字节流）复制文件
     */
    public void copyFileWithFileStream(String src, String des){
        // 1. 创建相关File类的对象
        File srcFile = new File(src);
        File desFile = new File(des);
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            // 2. 创建相关字节流
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(desFile);

            // 3. 数据的读入和写出
            byte[] buffer = new byte[50];
            int len; // 记录每次读入到buffer中字节的个数
            while ((len = fis.read(buffer)) != -1){
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 4. 关闭资源
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if (fis != null) fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
